package com.nami.gchat.infra.impl;

import com.nami.gchat.domain.repository.CacheDomainRepository;
import com.nami.gchat.types.constants.CommonConst;
import com.nami.gchat.types.utils.MsgUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.redis.utils.RedisTemplateKit;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class CacheDomainRepositoryImpl implements CacheDomainRepository {

    private final RedisTemplateKit redisTemplateKit;


    @Override
    public boolean checkIdempotent(String appKey, String userId, String clientMsgId) {
        if (StringUtils.isBlank(appKey) ||
            StringUtils.isBlank(userId)
            || StringUtils.isBlank(clientMsgId)) {
            return Boolean.FALSE;
        }
        boolean hasKey = redisTemplateKit.hasKey(MsgUtil.genRepeatMsgKey(appKey, userId, clientMsgId));

        if (!hasKey) {
            // 没有 key，说明根本没有缓存，或者是定期删除恰好删除了，直接返回 null
            return Boolean.FALSE;
        }
        Long expireTime = redisTemplateKit.getExpire(MsgUtil.genRepeatMsgKey(appKey, userId, clientMsgId));
        // 键值已过期
        if (expireTime <= 0) {
            // 没必要，待redis自己删除，减少一次网络io和redis自操作
//            redisTemplateKit.del(genRedisRepeatKey(identityNo, clientMsgId));
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    @Override
    public Long incrSeq(String appKey, String cid) {
        return redisTemplateKit.incr(MsgUtil.generateConverSeqKey(appKey, cid), CommonConst.BASE_NUM_1);
    }

}
